﻿var map = null;
var geocoder = null;
var flagMarker = 0;
var flagLoadDistrict = 0;
var gmarkers = [];
var i = 0;
var divVisible = '';
var numOfProject = 0;
var countCondition = '1=1';
var loadedStatus = 0;

var myWidth = 0, myHeight = 0;
function addLoadEvent(func, myLat, myLng, swBoundLat, swBoundLng, neBoundLat, neBoundLng, image) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {

        window.onload = func;
    }
    else {
        window.onload = function () {

            if (oldonload) {

                oldonload();

                func(myLat, myLng, swBoundLat, swBoundLng, neBoundLat, neBoundLng, image);
            }
            func(myLat, myLng, swBoundLat, swBoundLng, neBoundLat, neBoundLng, image);
        }

        func(myLat, myLng, swBoundLat, swBoundLng, neBoundLat, neBoundLng, image);
    }
}
function LoadBDQH(myLat, myLng, swBoundLat, swBoundLng, neBoundLat, neBoundLng, image) {

    var pointCenter = new GLatLng(myLat, myLng);
    var map = new GMap2(document.getElementById("GMap2"));
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.addControl(new GOverviewMapControl(new GSize(100, 100)));
    map.setCenter(pointCenter, 13);

    var pointSW = new GLatLng(swBoundLat, swBoundLng);
    var pointNE = new GLatLng(neBoundLat, neBoundLng);

    var groundOverlay = new GGroundOverlay(image,
           new GLatLngBounds(pointSW, pointNE));

    map.addOverlay(groundOverlay);
}
function calculateWindowSize() {
    if (typeof (window.innerWidth) == 'number') {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    }
    else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
}

function ResizeWindow() {
    calculateWindowSize();
    var container = document.getElementById('container');
    var rightpanel = document.getElementById('rightpanel');
    var leftpanel = document.getElementById('leftpanel');
    var markers = document.getElementById('markers');
    container.style.height = myHeight - container.offsetTop + "px";
    rightpanel.style.height = myHeight - container.offsetTop - rightpanel.offsetTop - 194 + "px";
    leftpanel.style.height = myHeight - container.offsetTop - leftpanel.offsetTop - 194 + "px";
    markers.style.height = myHeight - container.offsetTop - leftpanel.offsetTop - 194 + "px";
};

function load2(obj) {
   var city = $(obj).val();
    var X = $("#cbProvince option:selected").attr("X");
    var Y = $("#cbProvince option:selected").attr("Y");
    if (city != -1)
        map.setCenter(new GLatLng(X, Y), 12);
    scanMap();
   
}


function load() {
    //  CountAllProject();
    //if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("GMap2"));
    map.addControl(new GOverviewMapControl());
    map.enableScrollWheelZoom();
    map.enableRotation();
    var center = new GLatLng(10.769567636490475, 106.70642852783203);
    map.setCenter(center, 12);
    map.setMapType(G_NORMAL_MAP);
    geocoder = new GClientGeocoder();
    map.setUIToDefault();
    GEvent.addListener(map, "moveend", function () {
        var center = map.getCenter();

        if (loadedStatus == 0) {
            if (flagMarker == 0)
                scanMap();
        }
    });
    if (loadedStatus == 0) {
        if (flagMarker == 0)
            scanMap();
    }
    //}
}

// This function picks up the click and opens the corresponding info window
function Linkclicked(i) {
    GEvent.trigger(gmarkers[i], "click");
}

function scanMap() {
  //  CountAllProject();
    map.clearOverlays();
    var bounds = map.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    CreateMapMarker(southWest.lat(), southWest.lng(), northEast.lat(), northEast.lng());
}

function CreateMapMarker(southWest_lat, southWest_lng, northEast_lat, northEast_lng) {    
    getjson2(southWest_lat, southWest_lng, northEast_lat, northEast_lng);
}

function getjson2(_southWest_lat, _southWest_lng, _northEast_lat, _northEast_lng) {
    var count = 0;
    var Id = 0;
    var container = document.getElementById('listResult');
    var stringResultItem = '';
    var city = $("#cbProvince").val();
    var Cate = $("#cbServiceCategoly").val();
    var Price = $("#cbPriceGroup").val();
    if (city == 0) return;
    $.ajax({
        type: "POST",
        url: '/Tools/MMapServices.asmx/GetNewsList',
        cache: false,
        contentType: "application/json; charset=utf-8",
        data: '{' + $.Format('"southWest_lat":{0},"southWest_lng":{1},"northEast_lat":{2},"northEast_lng":{3},"city":{4},"Cate":{5},"Price":{6}', _southWest_lat, _southWest_lng, _northEast_lat, _northEast_lng, city, Cate,Price) + '}',
        
        dataType: "json",
        success: function (data) {
            data = eval("(" + data.d + ")");
            $.each(data, function (i, item) {
                count = count + 1;
                Id = item.DioNewsId;
                if (Id != -1) {
                    AddMarker(item, count);
                    stringResultItem += AddProjectItem(item, count, count);
                }
            });
            container.innerHTML = stringResultItem;
        },
        error: function (data) { }
    });
}

function getjson(previewUrl) {
    var count = 0;
    var Id = 0;
    var container = document.getElementById('listResult');
    var stringResultItem = '';
    $.ajax({
        type: "POST",
        url: '/Tools/MMapServices.asmx/GetSurvey',
        cache: false,
        contentType: "application/json; charset=utf-8",
        data: '{"A":' + 1 + '}',
        dataType: "json",
        success: function (data) {
            data = eval("(" + data.d + ")");
            console.log(data);
            $.each(data, function (i, item) {
                count = count + 1;
                Id = item.DioNewsId;
                if (Id != -1) {
                    AddMarker(item, count);
                    stringResultItem += AddProjectItem(item, count, count);
                }
            });
            container.innerHTML = stringResultItem;
        },
        error: function (data) { }
    });
}

function hideLoading() {
    $("#loading").hide();
}

function showLoading() {
    $("#loading").show();
}

function AddProjectItem(item, count, i) {
    var container = '';
    var _pData = {
        city: 3,
        Longtitude: item.X,
        Lattitude: item.Y,
        ImgUrl: item.ImageSmall,
        Title: item.Title,
        Intro: item.Des,
        Detail: item.Detail
    };

    var pattern = '<li id="div{0}"  onclick="javascript:Linkclicked({0});"> <img src="{1}" width="60" height="60"  onmouseover="changeMarkerIcon(this.id,{3});" onmouseout="resetMarkerIcon(this.id,{3});" onclick="javascript:Linkclicked({0});" >'
                            + '<a>{2}</a> </li>';
    if (item.ImgUrl.indexOf('~/Data') != -1)
        item.ImgUrl = item.ImgUrl.replace('~/Data', 'Data');
    container = $.Format(pattern, i, item.ImgUrl, item.Tittle, item.Catalogue);
    return container;

}

function AddCountResult(count, id) {
    $("#loading").show();
    if (count > 0 && id != -1) {
        document.getElementById('txtKetqua').innerHTML = 'Có ' + count + '/' + numOfProject + ' tài sản';
        hideLoading();
    }
    else {
        document.getElementById('txtKetqua').innerHTML = 'Đang load dữ liệu...';
        if (id == -1) {
            document.getElementById('txtKetqua').innerHTML = 'Không tìm thấy dữ liệu';
            hideLoading();
        }
    }
}

function AddMarker(item, i) {
    var Glat = '';
    var Glng = '';
    var myIcon = new GIcon(G_DEFAULT_ICON);
    var linkImage = getLinkForCatelogory(item);

    myIcon.image = linkImage+'map.png';
   // myIcon.shadow = linkImage+'map.png';
    myIcon.iconSize = new GSize(22, 37);
    myIcon.iconAnchor = new GPoint(10, 28);
    myIcon.infoWindowAnchor = new GPoint(9, 7);
    markerOptions = { icon: myIcon };

    Glng = item.Lattitude;
    Glat = item.Longtitude;
    //    Glat = item.Lattitude;
    //    Glng = item.Longtitude;
    var point = new GLatLng(Glat, Glng);
    var marker = new GMarker(point, markerOptions);
    map.addOverlay(marker);
    CreateDescription(item, marker, i);
    gmarkers[i] = marker;
}
function getLinkForCatelogory(item) {
    var Result = 'content/Map/css/img/'; 
    switch (item.Catalogue) {
        case 1:
            Result += "tieccuoi/";
            break;
        case 2:
            Result += "chupanhcuoi/";
            break;
        case 3:
            Result += "trangphuccuoi/";
            break;
        case 4:
            Result += "lamdep/";
            break;
        case 5:
            Result += "trangsuccuoi/";
            break;
        case 6:
            Result += "thiepcuoi/";
            break;
        case 7:
            Result += "hoacuoi/";
            break;
        case 8:
            Result += "dichvucuoi/";
            break;
        case 9:
            Result += "weddingplanner/";
            break;
    }
    return Result;
}
function CreateDescription(item, marker, i) {
    var sb = '';
    var sMoTa = '';
    var gia = '';
    var result = '';
    //    var price = item.PriceMain;
    var price = 10;
    if (item.PriceValue != '0') {
        //gia = FormatPrice(price) + ' ' + item.CurrencyId.toUpperCase() + ' ' + (item.Unit != 'md'? '/' + item.Unit:'');
        gia = FormatPrice(item.PriceValue) + ' VNĐ';
    }
    else
        gia = 'Thương lượng';
    if (item.ImgUrl.indexOf('~/Data') != -1)
        item.ImgUrl = item.ImgUrl.replace('~/Data', 'Data');
    sb += '<div class="map_view box">';
    sb += '<div class="map_close"></div>';
    sb += '<div class="map_top"></div>';
    sb += '<div class="map_contents box">';
    sb += '<div class="title">';
    sb += '<a href="http://www.diaoconline.vn/sieuthi/chitiet/' + item.ID + '/' + '" target="_blank" onclick="var w = window.open(this.href,this.target);return (w)?false:true">';
    sb += item.Tittle;
    sb += '</a></div>';
    sb += '<div class="img imgMap" style="float:left; padding:5px 5px 0 0" ><a href="#"><img src="' + item.ImgUrl + '" width="80" height="80"/></a></div>';
    sb += '<div class="divDesMap" style="padding-top:3px;">';
    sb += '<div class="address"> </div>';
    sb += '<div id="DivDes" style="padding-left: 86px">' + item.Intro + '<br/>' + '<span class="address"> Giá: ' + gia + '</span></div>';
    sb += '<div class="map_more alignR" style="text-align:right">';
    sb += '<a href="http://www.diaoconline.vn/sieuthi/chitiet/' + item.ID + '/' + '" target="_blank" onclick="var w = window.open(this.href,this.target);return (w)?false:true">Xem thông tin chi tiết</a>';
    sb += '</div></div></div></div>';

    var linkImage = getLinkForCatelogory(item);
    GEvent.addListener(marker, "click", function () {
        marker.openInfoWindowHtml(sb);
        document.getElementById('div' + i).style.background = 'url("content/Map/css/img/bgd.gif")';
        flagMarker = 1;
        divVisible = 'div' + i;
        marker.setImage(linkImage+'map_over.png');
    });
    GEvent.addListener(marker, "infowindowclose", function () {
        flagMarker = 0;
        document.getElementById('div' + i).style.background = "";
        marker.setImage(linkImage + 'map.png');
        divVisible = '';
    });
    GEvent.addListener(marker, "mouseover", function () {
        if (divVisible.replace('div', '') != i) {
            document.getElementById('div' + i).style.background = 'url("content/Map/css/img/bgd.gif")';
            marker.setImage(linkImage + 'map_over.png');
        }
    });
    GEvent.addListener(marker, "mouseout", function () {
        if (divVisible.replace('div', '') != i) {
            document.getElementById('div' + i).style.background = "";
            marker.setImage(linkImage + 'map.png');
        }
    });
}
$(window).load(function () {
    $("#loading").hide();
})

function FormatPrice(price) {
    var result = '';
    var i = 1;
    var length = price.toString().length;
    for (var len = length - 1; len >= 0; len--) {
        if ((i == 3 || i == 6 || i == 9) && i != length)
            result += price.toString().charAt(len) + ',';
        else result += price.toString().charAt(len);
        i++;
    }
    price = result;
    length = result.toString().length;
    result = '';
    for (var len1 = length - 1; len1 >= 0; len1--)
        result += price.toString().charAt(len1);
    return result;
}




function changeMarkerIcon(div, cate) {
    var linkImage = getLinkForCatelogory({ Catalogue: cate });
    gmarkers[div.replace('div', '')].setImage(linkImage+'map_over.png');
}

function resetMarkerIcon(div, cate) {
    var linkImage = getLinkForCatelogory({ Catalogue: cate });
    if (divVisible != div)
        gmarkers[div.replace('div', '')].setImage(linkImage+'map.png');
}

function RemoveDistrictList() {
    var sel = window.document.getElementById('ctl00_ContentPlaceHolder1_cboDistrict');
    for (var i = sel.children.length - 1; i >= 0; i--) {
        sel.remove(i);
    }
}

function stripHTML(oldString) {
    var newString = "";
    var inTag = false;
    for (var i = 0; i < oldString.length; i++) {

        if (oldString.charAt(i) == '<') inTag = true;
        if (oldString.charAt(i) == '>') {
            if (oldString.charAt(i + 1) == "<") {
                //dont do anything
            }
            else {
                inTag = false;
                i++;
            }
        }
        if (!inTag) newString += oldString.charAt(i);

    }

    return newString;
}

function keypress(e) {
    //Hàm dùng để ngăn người dùng nhập các ký tự khác ký tự số vào TextBox
    var keypressed = null;

    if (window.event) {
        keypressed = window.event.keyCode; //IE
    }
    else {
        keypressed = e.which; //NON-IE, Standard
    }

    if (keypressed == 62 || keypressed == 60) {
        return false;
    }

}

function FilterDioNews(typechange) {    
    scanMap();
}

